import {
  loginByUsername,
  logout,
  getInfo,
  getMenus
} from '@/api/login'
import {
  Message
} from 'element-ui'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { asyncRouterMap } from '@/router'

/**
 * 通过code判断是否有匹配的路由
 * @param menu
 * @param paths
 */
function hasPermission(menu, paths) {
  const path = paths.filter(path => {
    if (path.key === menu.code) {
      return path;
    }
    return false;
  })
  return path;
}

/**
 * 递归获取code-path对
 * @param asyncRouterMap
 */
function genRouterPaths(asyncRouterMap, paths) {
  asyncRouterMap.map(router => {
    if (router.children && router.children.length > 0) {
      genRouterPaths(router.children, paths)
    }
    paths.push({ key: router.authority, value: router.path });
    return true;
  })
  return paths
}

/**
 * 递归过滤菜单，将访问路径以前端配置的方式展现
 * @param permissionMenus
 * @param routers
 */
function filterMenus(permissionMenus, paths) {
  const menus = permissionMenus.filter(menu => {
    const path = hasPermission(menu, paths);
    if (path) {
      if (path.length > 0) {
        menu.path = path[0].value;
      }
      if (menu.children && menu.children.length) {
        menu.children = filterMenus(menu.children, paths)
      }
      return true
    }
    return false
  })
  return menus
}

/**
 * 菜单排序 orderNum越小越靠前
 * @param permissionMenus
 */
function sortMenus(permissionMenus) {
  permissionMenus.sort((a, b) => a.orderNum - b.orderNum)
  permissionMenus.map(menu => {
    if (menu.children && menu.children.length > 0) {
      sortMenus(menu.children)
    }
    return true;
  })
}

const user = {
  state: {
    user: '',
    status: '',
    code: '',
    token: getToken(),
    name: '',
    avatar: '',
    introduction: '',
    roles: [],
    menus: undefined,
    elements: undefined,
    permissionMenus: undefined,
    setting: {
      articlePlatform: []
    }
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_MENUS: (state, menus) => {
      state.menus = menus
    },
    SET_ELEMENTS: (state, elements) => {
      state.elements = elements
    },
    LOGIN_SUCCESS: () => {
      console.log('login success')
    },
    LOGOUT_USER: state => {
      state.user = ''
    },
    SET_PERMISSION_MENUS: (state, permissionMenus) => {
      state.permissionMenus = permissionMenus
    }
  },

  actions: {
    // 用户名登录
    LoginByUsername({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        loginByUsername(username, userInfo.password).then(response => {
          const data = response
          if (data.access_token === '' || data.access_token === undefined) {
            Message({
              message: '账户或密码错误！',
              type: 'warning'
            })
            return Promise.reject('error')
          } else {
            const token = 'Bearer ' + data.access_token;
            setToken(token)
            commit('SET_TOKEN', token);
            resolve()
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const data = response.data
          commit('SET_ROLES', 'admin')
          commit('SET_NAME', data.name)
          commit('SET_AVATAR', 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1542258438627&di=8dae550ef3923596cd08ca9a13b57fb0&imgtype=0&src=http%3A%2F%2Fpic.51yuansu.com%2Fpic3%2Fcover%2F01%2F69%2F80%2F595f67c2239cb_610.jpg')
          commit('SET_INTRODUCTION', data.description)
          const menus = {}
          for (let i = 0; i < data.menus.length; i++) {
            menus[data.menus[i].code] = true
          }
          commit('SET_MENUS', menus)
          const elements = {}
          for (let i = 0; i < data.elements.length; i++) {
            elements[data.elements[i].code] = true
          }
          commit('SET_ELEMENTS', elements)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
        getMenus().then(response => {
          const menus = genRouterPaths(asyncRouterMap, []);
          sortMenus(response.data[0].children);
          const permissionMenus = filterMenus(response.data[0].children, menus);
          commit('SET_PERMISSION_MENUS', permissionMenus)
        })
      })
    },

    // 第三方验证登录
    // LoginByThirdparty({ commit, state }, code) {
    //   return new Promise((resolve, reject) => {
    //     commit('SET_CODE', code)
    //     loginByThirdparty(state.status, state.email, state.code).then(response => {
    //       commit('SET_TOKEN', response.data.token)
    //       setToken(response.data.token)
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },

    // 登出
    LogOut({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        const token = state.token
        commit('SET_TOKEN', '')
        logout(token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_MENUS', undefined)
          commit('SET_ELEMENTS', undefined)
          commit('SET_PERMISSION_MENUS', undefined)
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({
      commit
    }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_MENUS', undefined)
        commit('SET_ELEMENTS', undefined)
        commit('SET_PERMISSION_MENUS', undefined)
        removeToken()
        resolve()
      })
    }
  }
}

export default user
